package com.sjh.tomcat;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SjhTomcatV1 {

    public static void main(String[] args) throws IOException {

        // 创建ServerSocket, 在8080端口监听
        ServerSocket serverSocket = new ServerSocket(8080);
        while(!serverSocket.isClosed()){
            Socket socket = serverSocket.accept();
            System.out.println("=======客户端正在8080端口监听=======");
            InputStream inputStream = socket.getInputStream();
            // 字节流转为字符流
            BufferedReader bufferedReader
                    = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String mes = null;
            System.out.println("=======接受到浏览器发送的数据=======");
            while((mes = bufferedReader.readLine()) != null) {
                if (mes.length() == 0) break;
                System.out.println(mes);
            }
            //回送-http响应方式
            OutputStream outputStream = socket.getOutputStream();
            //构建http响应头
            String httpRespHeader = "Http/1.1 200 OK\r\n" +
                    "Content-Type: text/html;charset=utf-8\r\n\r\n";
            //构建http响应体
            String httpResp = httpRespHeader + "hi, sjh!!!!";
            System.out.println("=======给浏览器放回的数据=======");
            System.out.println(httpResp);
            outputStream.write(httpResp.getBytes());

            outputStream.flush();
            outputStream.close();
            inputStream.close();
            socket.close();
        }
    }
}
